//
//  WBNewFeatureView.swift
//  传智微博
//
//  Created by zuxi li on 2017/3/23.
//  Copyright © 2017年 lingtu. All rights reserved.
//

import UIKit

class WBNewFeatureView: UIView {

    @IBOutlet var enterWeibo: UIButton!
    
    @IBOutlet var scrollView: UIScrollView!
    
    @IBOutlet var pageControl: UIPageControl!
    
    @IBAction func enterStatus(_ sender: Any) {
        removeFromSuperview()
    }
    
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        backgroundColor = UIColor.yellow
//    }
//    
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//

    
    class func newFeatureView() -> WBNewFeatureView {
        let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView
        // 从xib加载的视图默认是600*600的
        v.frame = UIScreen.main.bounds
        return v
    }
    
    override func awakeFromNib() {
        // 如果使用自动布局设置的界面，从Xib加载的界面，默认是600X600大小的
        // 添加4个图像视图
        let count = 4
        let rect = UIScreen.main.bounds
        for i in 0..<count {
            let imageName = "new_feature_\(i+1)"
            let iv = UIImageView(image: UIImage(named: imageName))
            // 设置大小
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            scrollView.addSubview(iv)
        }
        
        // 指定scrollView的输出
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.bounces = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        // 隐藏按钮
        enterWeibo.isHidden = true
        
        scrollView.delegate = self
        
    }

}

// MARK: - UIScrollViewDelegate
extension WBNewFeatureView: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 滚动到最后一个， 让视图删除
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        // 判断是否是最后一页
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }
        // 如果是倒数第二页显示按钮
        enterWeibo.isHidden = (page != scrollView.subviews.count - 1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 一旦滚动隐藏按钮
        enterWeibo.isHidden = true
        // 计算当前偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        pageControl.currentPage = page
        // 分页控件的隐藏
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
}
